﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;


namespace EIS_desktop
{
    public partial class PayRoll2 :Form
    {
        private int EmpId;
        private DateTime PayPeriod;
        private string Name;

        public PayRoll2(int empid, string payperiod,string name)
        {
            InitializeComponent();
            this.EmpId = empid;
            this.PayPeriod = Convert.ToDateTime("1-" + payperiod);
            this.Name = name;
        }

        public PayRoll2( )
        {
            InitializeComponent();
        }

        private void GetRates( )
        {
            SqlConnection sqlcon = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.AppSettings["constr"]);
            SqlDataAdapter sqladp = new SqlDataAdapter("select * from AdvPayRollRates where empid = " + this.EmpId, sqlcon);
            DataTable dt = new DataTable();
            sqladp.Fill(dt);
            dataGridView1.DataSource = dt;
         }   

        private void PayRoll2_Load(object sender, EventArgs e)
        {
            txtName.Text = this.Name;
            lblPeriod.Text = "PayRoll for the period of " + PayPeriod.ToLongDateString();
            GetRates();
        }

        private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (dataGridView1.Columns[e.ColumnIndex].Name.ToLower() == "percentage")
            {
                DataGridViewComboBoxCell combocell = new DataGridViewComboBoxCell();
                combocell.Items.AddRange("70", "75", "80");
                dataGridView1[e.ColumnIndex, e.RowIndex] = combocell;
            }
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
        }

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {

            DataGridView dgv = dataGridView1;
            DataGridViewRow dgvrow = dgv.Rows[e.RowIndex];
            switch (dataGridView1.Columns[e.ColumnIndex].Name)
            {

                case "Start Date":
                    if (DateTime.Compare((DateTime)dgvrow.Cells["Start Date"].Value, this.PayPeriod) == -1)
                        dgvrow.Cells["Start Date"].ErrorText = "date should not be earlier than " + this.PayPeriod.ToLongDateString();
                    else
                        dgvrow.Cells["Start Date"].ErrorText = string.Empty;
                    if (e.RowIndex > 0)
                        if (DateTime.Compare((DateTime)dgvrow.Cells["Start Date"].Value, (DateTime)dataGridView1.Rows[e.RowIndex - 1].Cells["End Date"].Value) == -1)
                        {
                            dgvrow.Cells["Start Date"].ErrorText = "Start Date should be earlier that previous End Date";
                        }
                        else
                            dgvrow.Cells["Start Date"].ErrorText = string.Empty;
                    break;
                case "End Date":
                    if (DateTime.Compare((DateTime)dgvrow.Cells["End Date"].Value, this.PayPeriod) == -1)
                        dgvrow.Cells["End Date"].ErrorText = "date should not be realier than " + this.PayPeriod.ToLongDateString();
                    else
                        dgvrow.Cells["End Date"].ErrorText = string.Empty;
                    if (DateTime.Compare((DateTime)dgvrow.Cells["End Date"].Value, (DateTime)dataGridView1.Rows[e.RowIndex].Cells["Start Date"].Value) == -1)
                    {
                        dgvrow.ErrorText = "End Date should be later that start Date";
                    }
                    else
                        dgvrow.ErrorText = string.Empty;
                    break;
                case "Client Rate":
                    dgvrow.Cells["Actual Rate"].Value =(Convert.ToInt32(dgvrow.Cells["Percentage"].Value) * (double)dgvrow.Cells["Client Rate"].Value) / 100;
                    
                    break;
                case "Paid Rate":
                    dgvrow.Cells["Difference"].Value =(double)dgvrow.Cells["Actual Rate"].Value -(double)dgvrow.Cells["Paid Rate"].Value;
                    break;
                    
            }

        }

        private void CalculateHours( )
        {
           double hrsPaidFromWithhold=0;
           double hrsworkedCurrentMonth = 0;
           double Totalhrspaid = 0;

            foreach (DataGridViewRow drow in dataGridView1.Rows)
            {
              if (drow.Cells["Hours Worked Current Month"].Value!=DBNull.Value)
             hrsworkedCurrentMonth += Convert.ToDouble(drow.Cells["Hours Worked Current Month"].Value);
                if (drow.Cells["Hours Paid With Hold"].Value != DBNull.Value)
                     hrsPaidFromWithhold+= Convert.ToDouble(drow.Cells["Hours Paid With Hold"].Value);
                if (drow.Cells["Total Hours Paid"].Value != DBNull.Value)
                    Totalhrspaid  += Convert.ToDouble(drow.Cells["Total Hours Paid"].Value);
            }
            txtHrsPaidFromWithHold.Text  = hrsPaidFromWithhold.ToString();
            txtHrsWorkedCurMon.Text = hrsworkedCurrentMonth.ToString();
            txtTotalHrsPaid.Text = Totalhrspaid.ToString();

        }
        private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        private void dataGridView1_RowLeave(object sender, DataGridViewCellEventArgs e)
        {
            dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
            CalculateHours();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
           SqlConnection con= new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.AppSettings["constr"]);
           
           foreach (DataGridViewRow drow in dataGridView1.Rows)
           {
               SqlCommand cmd = new SqlCommand("INSERT INTO [EmployeeInfo].[dbo].[AdvPayrollRates] ([EmpId],[Start Date],[End Date]," +
               "[Percentage] ,[Client Rate] ,[Actual Rate],[Paid Rate],[Difference],[Hours Worked Current Month],[Hours Paid With Hold]" +
          ",[Total Hours Paid]) VALUES (@empid,@sd,@ed,@percent,@cr,@ar,@pr,@diff,@hrswrkcurmon,@hrspaidWH,@tothrspaid)");
               cmd.Connection = con;
               cmd.CommandType = CommandType.Text;
               cmd.Parameters.Add(new SqlParameter("@empid", drow.Cells[0].Value));
               cmd.Parameters.Add(new SqlParameter("@sd", drow.Cells[1].Value));
               cmd.Parameters.Add(new SqlParameter("@ed", drow.Cells[2].Value));
               cmd.Parameters.Add(new SqlParameter("@percent", drow.Cells[3].Value));
               cmd.Parameters.Add(new SqlParameter("@cr", drow.Cells[4].Value));
               cmd.Parameters.Add(new SqlParameter("@ar", drow.Cells[5].Value));
               cmd.Parameters.Add(new SqlParameter("@pr", drow.Cells[6].Value));
               cmd.Parameters.Add(new SqlParameter("@diff", drow.Cells[7].Value));
               cmd.Parameters.Add(new SqlParameter("@hrswrkcurmon", drow.Cells[8].Value));
               cmd.Parameters.Add(new SqlParameter("@hrspaidWH", drow.Cells[9].Value));
               cmd.Parameters.Add(new SqlParameter("@tothrspaid", drow.Cells[10].Value));
               con.Open();
               cmd.ExecuteNonQuery();
               con.Close();
           }
           SqlCommand SQLcmd = new SqlCommand("INSERT INTO [EmployeeInfo].[dbo].[AdvPayroll] ([EmpID],[PayPeriod]" +
               ",[CurrentMonthWithHoldAmount],[WithHoldBalanceForward],[SalaryFromWithHold]," +
                "[PerDiem_otherPayWithHeld],[BalanceWithHeldAmount],[FilingFeeDeduction],[OtherAdjustment],[Total]" +
              ",[RequireWithHodling]) VALUES (@empid,@payperiod,@curmonWHamount,@WHBalfor,@salfromWH,@perdiemWH,@balWH,@ffdeduc" +
              "@otheraduj,@total,@reqWH)");
           SQLcmd.Connection = con;
           SQLcmd.CommandType = CommandType.Text;
           SQLcmd.Parameters.Add(new SqlParameter("@empid", this.EmpId));
           SQLcmd.Parameters.Add(new SqlParameter("@payperiod", this.lblPeriod.Text));
            SQLcmd.Parameters.Add(new SqlParameter("@curmonWHamount",txtCurMonWithHeldAmount));
            SQLcmd.Parameters.Add(new SqlParameter("@WHBalfor",txtWithHeldBalForw.Text));
            SQLcmd.Parameters.Add(new SqlParameter("@salfromWH", txtSalFromWithHeld.Text));
            SQLcmd.Parameters.Add(new SqlParameter("@perdiemWH", txtPerDiemWithHeld.Text));
            SQLcmd.Parameters.Add(new SqlParameter("@balWH", txtBalWithHeld.Text));
            SQLcmd.Parameters.Add(new SqlParameter("@ffdeduc", txtFilingFeeDeduc.Text));
            SQLcmd.Parameters.Add(new SqlParameter("@otheraduj", txtOtherAdjus.Text));
            SQLcmd.Parameters.Add(new SqlParameter("@total", txtTotalPayRoll.Text));
            SQLcmd.Parameters.Add(new SqlParameter("@reqWH", (rbRequireWHYes.Checked == true)? "yes": "no"));
            con.Open();
            SQLcmd.ExecuteNonQuery();
            con.Close();
        }

       
    }
}